package com.formerlyknownasprince.wheresmystuff;

import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.formerlyknownasprince.wheresmystuff.models.LoginManager;
import com.formerlyknownasprince.wheresmystuff.models.User;
import com.formerlyknownasprince.wheresmystuff.models.Item;
/**
 * @author      Tim Swihart 		<email obscured since this file is public>
 * @version     0.1               
 * @since       2013-03-04
 */
public class ItemListActivity extends ListActivity implements
		ActionBar.OnNavigationListener {

	/**
	 * The serialization (saved instance state) Bundle key representing the
	 * current dropdown position.
	 */
	private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
	private User currentUser;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_item_list);

		currentUser = LoginManager.getInstance().getUser();
		
		setListAdapter(new ItemListAdapter(this, R.layout.item_list_row));
		
		/*AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Well then...");
		builder
			.setMessage(String.valueOf(currentUser.getItems().size()))
			.setPositiveButton("Sure", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					dialog.cancel();
				}
			  });
		builder.show();*/
	}
	public void onListItemClick(ListView l, View v, int position, long id) {
        // Open the ItemView activity for the item at the selected position
		Intent intent = new Intent(getApplicationContext(), ItemInfoActivity.class);
		Bundle bundle = new Bundle();
		bundle.putInt("item_id", position);
		intent.putExtras(bundle);
		startActivity(intent);
    }

	
	@Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {     
		switch (menuItem.getItemId()) {
			case R.id.action_item_add:
				startActivityForResult(new Intent(getApplicationContext(),AddItemActivity.class), 1);
				break;
			case R.id.action_search:
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(R.string.error_dialog_title);
				builder
					.setMessage("This functionality isn't implemented, sorry!")
					.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int id) {
							dialog.cancel();
						}
					  });
				builder.show();
				break;
		}
        return true;
    }
	
		
	@Override
	public void onResume() {
		super.onResume();
		getListView().invalidateViews();
		getListView().requestLayout();
		//this.invalidateViews();
		/*final ArrayAdapter<Item> adapter = ((ArrayAdapter<Item>) getListAdapter());
		runOnUiThread(new Runnable() {
		    public void run() {
		        adapter.notifyDataSetChanged();
		    }
		});*/
		
	}


	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		// Restore the previously serialized current dropdown position.
		if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
			getActionBar().setSelectedNavigationItem(
					savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// Serialize the current dropdown position.
		outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
				.getSelectedNavigationIndex());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.item_list, menu);
		return true;
	}

	public boolean onNavigationItemSelected(int position, long id) {
		// When the given dropdown item is selected, show its contents in the
		// container view.
		/*Fragment fragment = new ItemSectionFragment();
		Bundle args = new Bundle();
		args.putInt(ItemSectionFragment.ARG_SECTION_NUMBER, position);
		fragment.setArguments(args);
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.container, fragment).commit();*/
		return true;
	}

	
	/**
	 * An Adapter to render a list of items. Will be separated out into a 
	 * fragment eventually
	 * @author chronon
	 *
	 */
	public class ItemListAdapter extends BaseAdapter {
        private Activity context;
        private int listResourceId;
        //List<Item> items;
       
        public ItemListAdapter(Activity ctx, int resId) {
                this.context = ctx;
                this.listResourceId = resId;
        }
       
        public int getCount() {
                return currentUser.getItems().size();
        }

        public Item getItem(int arg0) {
                return currentUser.getItems().get(arg0);
        }

        public long getItemId(int position) {
                return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
                Item i = currentUser.getItems().get(position);
                View itemRow = (LinearLayout) convertView;
                if (convertView == null) {
                        itemRow = (LinearLayout) context.getLayoutInflater().inflate(listResourceId, parent, false);
                }
                //if (itemRow != null)
                TextView itemName = (TextView) itemRow.findViewById(R.id.itemName);
                itemName.setText(i.getName());
                TextView itemStub = (TextView) itemRow.findViewById(R.id.itemStub);
                itemStub.setText(i.getDescription());
               
                return itemRow;
        }
       
}


}
